package serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import domain.SensorData;

public class XmlSerializer implements ISerializer {
	private JAXBContext jc;
	Unmarshaller unmarshaller;
	Marshaller marshaller;

	public XmlSerializer() throws JAXBException {
		jc = JAXBContext.newInstance(SensorData.class);
		unmarshaller = jc.createUnmarshaller();
		marshaller = jc.createMarshaller();
	}

	public SensorData decode(byte[] buf) {
		try {
			ByteArrayInputStream bis = new ByteArrayInputStream(buf);

			SensorData sensorData = (SensorData) unmarshaller.unmarshal(bis);
			return sensorData;
		} catch (Exception e) {
			System.err.println("Error occured, while parsing XML. Details: "
					+ e.getMessage());
		}
		return null;
	}

	public byte[] encode(SensorData obj) {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			Marshaller marshaller = jc.createMarshaller();
			marshaller.marshal(obj, bos);
			return bos.toByteArray();
		} catch (Exception e) {
			System.err.println("Error occured, while building XML. Details: "
					+ e.getMessage());
		}
		return null;
	}
}
